package com.mornd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mornd.entity.Menu;
import com.mornd.entity.Role;
import com.mornd.mapper.RoleMapper;
import com.mornd.service.RoleService;
import com.mornd.vo.RoleVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.io.Serializable;
import java.util.List;

/**
 * @author mornd
 * @date 2021/1/6 - 20:45
 */
@Service
@Transactional(readOnly = true,rollbackFor = Exception.class)
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
    /**
     * 查询角色集合
     *
     * @param roleVo
     * @return
     */
    @Override
    public IPage<Role> findList(RoleVo roleVo) {
        IPage<Role> page = new Page<>(roleVo.getPage(),roleVo.getLimit());
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        //查询条件
        wrapper.like(!ObjectUtils.isEmpty(roleVo.getCode()),"code",roleVo.getCode());
        wrapper.like(!ObjectUtils.isEmpty(roleVo.getName()),"name",roleVo.getName());
        //默认按创建时间降序
        wrapper.orderByDesc("gmt_create");
        return super.page(page,wrapper);
    }

    /**
     * 根据角色id查询该角色下是否有对应的用户
     *
     * @param roleId
     * @return
     */
    @Override
    public int checkRoleIfExistByUser(Integer roleId) {
        return getBaseMapper().checkRoleIfExistByUser(roleId);
    }

    /**
     * 根据角色id在关系表添加该角色的菜单
     *
     * @param roleId
     * @param mids
     * @return
     */
    @Override
    @Transactional(readOnly = false,rollbackFor = Exception.class)
    public int addMenuByRoleId(Integer roleId, List<Integer> mids) {
        return getBaseMapper().addMenuByRoleId(roleId,mids);
    }

    /**
     * 根据角色id查询对应的菜单
     *
     * @param RoleId
     * @return
     */
    @Override
    public List<Integer> findMenuByRoleId(Integer RoleId) {
        return getBaseMapper().findMenuByRoleId(RoleId);
    }

    /**
     * 根据角色id删除角色菜单表的关系
     * @param roleId
     * @return
     */
    @Override
    @Transactional(readOnly = false,rollbackFor = Exception.class)
    public int deleteRoleAndMenuRelation(Serializable roleId) {
        return getBaseMapper().deleteRoleAndMenuRelation(roleId);
    }

    /**
     * 根据 ID 删除
     * 重写mp的方法
     * 删除角色菜单表中的数据
     * @param id 主键ID
     */
    @Override
    @Transactional(readOnly = false,rollbackFor = Exception.class)
    public boolean removeById(Serializable id) {
        getBaseMapper().deleteRoleAndMenuRelation(id);
        return super.removeById(id);
    }
}
